import 'dart:convert';

import 'package:fig/sqlite/table_media_category.dart';
import 'package:fig/sqlite/table_media.dart';
import 'package:fig/utils/config.dart';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';

class GeneralSpider {
  static int currentPage = 1;
  static String baseSpiderUrl;

  GeneralSpider(); // 匿名构造函数

  static loadData(String spiderUrl) async {
    baseSpiderUrl = spiderUrl;

    while (await loop(spiderUrl, currentPage)) {
      currentPage++;
      print('准备采集页码:$currentPage');
    }

    print('爬虫采集完毕！');
    Config.spiderRunning = false;
  }

  static Future<bool> loop(String spiderUrl, int page) async {
    // https://cj.okzy.tv/inc/feifei3ckm3u8s/?ac=videolist&p=10&h=       OK云 60414
    // https://cj.okzy.tv/inc/feifei3down/?ac=videolist&p=10&h=          OK云 39191
    // http://caiji.kuyun98.com/inc/s_feifeikkm3u8/?ac=videolist&p=10&h= 酷云 45997
    // http://caiji.kuyun98.com/inc/s_feifei3down/?ac=videolist&p=10&h=  酷云 30699
    //var url = '$spiderUrl?ac=videolist&p=$page&h=168';
    var url = '$spiderUrl?ac=videolist&p=$page&h=24';
    int countPage = 1;

    // try {
      Response response = await http.get(url);
      if (response.statusCode != 200) {
        print('Request failed with status: ${response.statusCode}.');
        return false;
      }

      print('debug:response.url:$url');
      print('debug:response.body:${response.body}');
      var jsonResponse = jsonDecode(response.body);
      int status = jsonResponse['status'];
      if (status != 200) {
        return false;
      }

      //int currentPage = int.parse(jsonResponse['page']['pageindex']); // 不需要这个
      int _countPage = int.parse(jsonResponse['page']['pagecount']);

      // 处理分类
      // 后面不重复采集
      if (page == 1) {
        await TableMediaCategory().initCategories(jsonResponse['list']);
      }
      if (countPage < _countPage) {
        countPage = _countPage;
      }

      // 处理正式数据
      await TableMedia().initMedias(jsonResponse['data']);

    // } catch (e) {
    //   print('spider loadData error:$e');
    //   return false;
    // }

    print('当前页：$page 总页数 countPage：$countPage');

    return page < countPage;
  }
}
